package com.example.myapplication

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.database.Cursor
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.ContactsContract.CommonDataKinds.Organization.TITLE
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import kotlinx.coroutines.selects.whileSelect
import java.io.IOException
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(),ServiceConnection {
    val TAG = "MainActivityl"
    val Channel_ID = "my channel"
    val Notification_ID = 1
    var binder:MusicService.MusicBinder? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        val radio = findViewById<Button>(R.id.button6)
        radio.setOnClickListener {
            val notificationManager :NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val builder: Notification.Builder
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(Channel_ID, "test", NotificationManager.IMPORTANCE_HIGH)
                notificationManager.createNotificationChannel(notificationChannel)
                builder = Notification.Builder(this, Channel_ID)
            } else {
                builder = Notification.Builder(this)
            }

            val intent = Intent(this,MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

            val notification:Notification=builder.setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("musicname")
                .setContentText(binder!!.musicName)
                .setPriority(Notification.PRIORITY_HIGH)
                .setContentIntent(pendingIntent)
                .build()// set content text
            notificationManager.notify(Notification_ID, notification)
        }


        if (ContextCompat.checkSelfPermission(
                this,
                "android.permission.READ_MEDIA_AUDIO"
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf("android.permission.READ_MEDIA_AUDIO"),
                0
            )
        } else {
            startMusicService()
        }

        val seekBar=findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(
                seekBar: SeekBar,
                progress: Int,
                fromUser: Boolean
            ) {
                if (fromUser) {
                    binder ?. currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

    }


    fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                Channel_ID,
                "My Channel Name",
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "Channel description"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }

    fun startMusicService() {
        val intent = Intent( this, MusicService::class.java)
        intent.putExtra(MusicService.Commond,  1)
        startService(intent)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }
    fun onPlay(v:View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
    }
    fun onPause(v:View) {
        val intent = Intent( this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 2)
        startService(intent)
    }
    fun onStop(v:View) {
        val intent = Intent( this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 3)
        startService(intent)
    }
     fun onNext(v:View) {
         val intent = Intent( this, MusicService::class.java)
         intent.putExtra(MusicService.Commond, 4)
         startService(intent)
     }
    fun onPrev(v:View) {
        val intent = Intent( this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 5)
        startService(intent)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        startMusicService()
    }

    @SuppressLint("Range")


    override fun onDestroy() {
        super.onDestroy()
        unbindService(  this)
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder=null
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder=service as MusicService.MusicBinder
        thread {
            while (binder!=null){
                Thread.sleep(1000)
                runOnUiThread {
                    val seekBar=findViewById<SeekBar>(R.id.seekBar)
                    seekBar.max=binder!!.duration
                    seekBar.progress=binder!!.currentPosition
                    val textView_mm=findViewById<TextView>(R.id.textView_mn)
                    textView_mm.text=binder!!.musicName
                    val textView_count=findViewById<TextView>(R.id.textView_count)
                    textView_count.text="${binder!!.currentIndex+1}/${binder?.size }"
                }
            }
        }
    }
}